<template>
    <div :style="{ width: `${props.width}px` }" class="h-full  flex flex-col border-r border-gray-200 bg-gray-50">
        <div class="sticky top-0 z-10 bg-gray-50 border-gray-200">
            <div class="p-4 pb-0">
                <div class="flex justify-center">
                    <button @click="refreshTree" :style="{ width: `${props.width * 0.8}px` }"
                        class="mb-4 flex items-center justify-center px-4 py-2 text-white rounded-lg bg-green-500 hover:bg-green-600 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-green-300">
                        <i class="fa fa-refresh text-white hover:text-gray-100 transition-colors duration-200 mr-2"></i>
                        <span>刷新文件</span>
                    </button>
                </div>

                <!-- 新增：文件树/大纲切换选项 -->
                <div class="flex justify-center mb-4 border-b border-gray-200">
                    <div @click="activeTab = 'tree'"
                        :class="activeTab === 'tree' ? 'border-b-2 border-green-500 text-green-600' : 'text-gray-500 hover:text-gray-700'"
                        class="flex-1 max-w-[120px] px-3 py-2 text-center text-sm font-medium cursor-pointer transition-colors duration-200">
                        <i class="fa fa-folder-open-o mr-1"></i>文件树
                    </div>
                    <div @click="activeTab = 'outline'"
                        :class="activeTab === 'outline' ? 'border-b-2 border-green-500 text-green-600' : 'text-gray-500 hover:text-gray-700'"
                        class="flex-1 max-w-[120px] px-3 py-2 text-center text-sm font-medium cursor-pointer transition-colors duration-200">
                        <i class="fa fa-list-ul mr-1"></i>大纲
                    </div>
                </div>
            </div>
        </div>
        <div class="flex-1 overflow-y-auto p-4 pt-0 space-y-2">
            <FileNode v-show="activeTab === 'tree'" v-for="item in treeData" :key="item.path" :node="item"
                @navigate="navigateToFile" @show-context-menu="handleContextMenu" />
            <FileOutline v-show="activeTab === 'outline'" :content="props.markdownContent" />
        </div>

        <!-- 新增：右键菜单组件 -->
        <FileMenu v-if="contextMenu.isOpen" :isOpen="contextMenu.isOpen" :x="contextMenu.x" :y="contextMenu.y"
            :node="contextMenu.node" @close="closeContextMenu" @action="handleContextMenuAction" />
    </div>
</template>

<script setup>

const loading = ref(false)
const error = ref('')
const treeData = ref([])
const currentFile = ref('')
const activeTab = ref('tree') // 新增：当前激活的选项

// 新增：右键菜单状态
const contextMenu = ref({
    isOpen: false,
    x: 0,
    y: 0,
    node: null
})

const props = defineProps({
    width: {
        type: Number,
        required: true
    },
    markdownContent: {
        type: String,
        required: true
    }
})

const emit = defineEmits(['update:markdownContent']);

onMounted(async () => {
    await refreshTree()
})

const { getMarkdown, getFileTree, deleteFile, renameFile, deleteFolder, newFile, newFolder } = useApi()

// 刷新文件树
const refreshTree = async () => {
    loading.value = true
    error.value = ''

    try {
        const response = await getFileTree(null)
        if (response.code != 200) {
            throw new Error(`HTTP error! msg: ${response.msg}`)
        }
        treeData.value = [response.data.tree]

        if (currentFile.value != '') {
            navigateToFile(currentFile.value)
        }
    } catch (err) {
        error.value = err.message || '获取文件树失败'
    } finally {
        loading.value = false
    }
}

// 导航到文件
const navigateToFile = async (path) => {
    // if (currentFile.value === path) return
    currentFile.value = path

    const now_filename = useState("current_filename")
    now_filename.value = path.substring(path.replaceAll("\\", "/").lastIndexOf("/") + 1)

    loading.value = true
    error.value = ''

    try {
        const response = await getMarkdown({
            path: path
        })
        if (response.code != 200) {
            throw new Error(`HTTP error! status: ${response.status}`)
        }
        // 将当前 markdown 路径 保存到 state
        const usePath = useState('path')
        usePath.value = path
        console.log(usePath.value)

        let content = await response.data

        emit('update:markdownContent', content);
    } catch (err) {
        error.value = err.message || '加载文件失败'
    } finally {
        loading.value = false
    }
}


// 新增：处理右键菜单显示
const handleContextMenu = (event) => {
    contextMenu.value = {
        isOpen: true,
        x: event.x,
        y: event.y,
        node: event.node
    }
}

// 新增：关闭右键菜单
const closeContextMenu = () => {
    contextMenu.value.isOpen = false
}

// 新增：处理右键菜单项点击
const handleContextMenuAction = (action, node) => {
    switch (action) {
        case 'newFolder':
            handleNewFolder(node)
            break
        case 'newFile':
            handleNewFile(node)
            break
        case 'renameFolder':
            handleRenameFolder(node)
            break
        case 'deleteFolder':
            handleDeleteFolder(node)
            break
        case 'renameFile':
            handleRenameFile(node)
            break
        case 'deleteFile':
            handleDeleteFile(node)
            break
    }
}

// 新增：处理新建文件夹
const handleNewFolder = async (node) => {
    const folderName = prompt('请输入新文件夹名称')
    if (!folderName) return

    try {
        const response = await newFolder({
            parentPath: node.path,
            name: folderName
        })

        if (response.code != 200) {
            throw new Error(`HTTP error! msg: ${response.msg}`)
        }

        await refreshTree()
    } catch (err) {
        alert(`创建文件夹失败: ${err.message}`)
    }
}

// 新增：处理新建文件
const handleNewFile = async (node) => {
    const fileName = prompt('请输入新文件名称（包括扩展名）')
    if (!fileName) return

    try {
        const response = await newFile({
            parentPath: node.path,
            name: fileName
        })

        if (response.code != 200) {
            throw new Error(`HTTP error! msg: ${response.msg}`)
        }

        await refreshTree()
    } catch (err) {
        alert(`创建文件失败: ${err.message}`)
    }
}

// 新增：处理重命名文件夹
const handleRenameFolder = async (node) => {
    const newName = prompt('请输入新名称', node.name)
    if (!newName || newName === node.name) return

    try {
        const response = await fetch('/api/rename-folder', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                path: node.path,
                newName
            })
        })

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`)
        }

        await refreshTree()
    } catch (err) {
        alert(`重命名文件夹失败: ${err.message}`)
    }
}

// 新增：处理删除文件夹
const handleDeleteFolder = async (node) => {
    if (!confirm(`确定要删除文件夹 "${node.name}" 吗？`)) return

    try {
        const response = await deleteFolder({
            path: node.path
        })

        if (response.code != 200) {
            throw new Error(`HTTP error! msg: ${response.msg}`)
        }

        await refreshTree()
    } catch (err) {
        alert(`删除文件夹失败: ${err.message}`)
    }
}

// 新增：处理重命名文件
const handleRenameFile = async (node) => {
    const newName = prompt('请输入新名称', node.name)
    if (!newName || newName === node.name) return

    try {
        const response = await renameFile({
            path: node.path,
            newName
        })

        if (response.code != 200) {
            throw new Error(`HTTP error! msg: ${response.msg}`)
        }

        await refreshTree()
    } catch (err) {
        alert(`重命名文件失败: ${err.message}`)
    }
}

// 新增：处理删除文件
const handleDeleteFile = async (node) => {
    if (!confirm(`确定要删除文件 "${node.name}" 吗？`)) return

    try {
        const response = await deleteFile({
            path: node.path
        })

        if (response.code != 200) {
            throw new Error(`HTTP error! msg: ${response.msg}`)
        }

        await refreshTree()
    } catch (err) {
        alert(`删除文件失败: ${err.message}`)
    }
}
</script>